#include <dirent.h>
#include <stdio.h>
// #include "func.h"
#include <sys/stat.h>
#include <time.h>
#include <string.h>

int getFileInfo(char *fileName, struct stat *fileInfo);

int main() {
    struct stat fileInfo;
    getFileInfo("/home/wyf/网络编程与系统编程/ls/build/CMakeFiles", &fileInfo);
    printf("\tfilename\n");


    return 0;
}

int accessChange(unsigned int access, char *accessStr) {
    (access & S_IFMT) == S_IRUSR ? strcat(accessStr, "r") : strcat(accessStr, "-");
    (access & S_IFMT) == S_IWUSR ? strcat(accessStr, "w") : strcat(accessStr, "-");
    (access & S_IFMT) == S_IXUSR ? strcat(accessStr, "x") : strcat(accessStr, "-");
    (access & S_IFMT) == S_IRGRP ? strcat(accessStr, "r") : strcat(accessStr, "-");
    (access & S_IFMT) == S_IWGRP ? strcat(accessStr, "w") : strcat(accessStr, "-");
    (access & S_IFMT) == S_IXGRP ? strcat(accessStr, "x") : strcat(accessStr, "-");
    (access & S_IFMT) == S_IROTH ? strcat(accessStr, "r") : strcat(accessStr, "-");
    (access & S_IFMT) == S_IWOTH ? strcat(accessStr, "w") : strcat(accessStr, "-");
    (access & S_IFMT) == S_IXOTH ? strcat(accessStr, "x") : strcat(accessStr, "-");

    return 0;
}

int getFileInfo(char *fileName, struct stat *fileInfo) {
    if (stat(fileName, fileInfo) < 0) {
        printf("Error_getFileInfo");
        return -1;
    }
    unsigned int mask = 0000777;
    unsigned int access = mask & fileInfo->st_mode;
    // printf("%o\t%d\t", access, fileInfo->st_uid);
    // printf("%ld\n", fileInfo->st_atimespec);
    if ((fileInfo->st_mode & S_IFMT) == S_IFDIR)
        printf("d");
    char accessStr[15];
    memset(accessStr, 0, sizeof(char) * 15);
    // accessChange(access, accessStr);
    // accessChange(fileInfo->st_mode, accessStr);
    (fileInfo->st_mode & S_IRUSR) == S_IRUSR ? strcat(accessStr, "r") : strcat(accessStr, "-");
    (fileInfo->st_mode & S_IWUSR) == S_IWUSR ? strcat(accessStr, "w") : strcat(accessStr, "-");
    (fileInfo->st_mode & S_IXUSR) == S_IXUSR ? strcat(accessStr, "x") : strcat(accessStr, "-");
    (fileInfo->st_mode & S_IRGRP) == S_IRGRP ? strcat(accessStr, "r") : strcat(accessStr, "-");
    (fileInfo->st_mode & S_IWGRP) == S_IWGRP ? strcat(accessStr, "w") : strcat(accessStr, "-");
    (fileInfo->st_mode & S_IXGRP) == S_IXGRP ? strcat(accessStr, "x") : strcat(accessStr, "-");
    (fileInfo->st_mode & S_IROTH) == S_IROTH ? strcat(accessStr, "r") : strcat(accessStr, "-");
    (fileInfo->st_mode & S_IWOTH) == S_IWOTH ? strcat(accessStr, "w") : strcat(accessStr, "-");
    (fileInfo->st_mode & S_IXOTH) == S_IXOTH ? strcat(accessStr, "x") : strcat(accessStr, "-");
    printf("%s\t", accessStr);
    struct tm t;
    char date_time[64];
    strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", localtime_r(&fileInfo->st_ctim.tv_sec, &t));
    printf("%s\t", date_time);

    return 0;
}